package net.maku.framework.common.utils;

import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.function.Function;

/**
 * 文件工具类
 *
 * @author mxf
 */
public class DownloadUtils {

    /**
     * 根据地址获得数据的字节流
     *
     * @param imgUrl   网络连接地址
     * @return
     */
    public static InputStream getByteFormNetUrl(String imgUrl) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imgUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(60 * 1000);
            InputStream inputStream = httpURLConnection.getInputStream();
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //httpURLConnection.disconnect();
        }
        return null;
    }

       public static String download(String imgUrl,Function<InputStream,String> T) {
           HttpURLConnection httpURLConnection = null;
           try {
               URL url = new URL(imgUrl);
               httpURLConnection = (HttpURLConnection) url.openConnection();
               httpURLConnection.setRequestMethod("GET");
               httpURLConnection.setConnectTimeout(60 * 1000);
               InputStream inputStream = httpURLConnection.getInputStream();
               return T.apply(inputStream);
           } catch (Exception e) {
               e.printStackTrace();
           } finally {
               httpURLConnection.disconnect();
           }
           return null;
      }
    /**
     * 根据地址获得数据的字节流
     *
     * @param imgUrl   网络连接地址
     * @param savePath 图片存储本地地址
     * @return
     */
    public static byte[] getByteFormNetUrl(String imgUrl, String savePath) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imgUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5 * 1000);
            InputStream inputStream = httpURLConnection.getInputStream();
            byte[] btImg = readInputStream(inputStream, savePath);
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpURLConnection.disconnect();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inputStream 输入流
     * @param savePath    图片存储本地地址
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream, String savePath) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        //输出文件流
        OutputStream os = new FileOutputStream(savePath);
        int len = 0;
        //写入
        while ((len = inputStream.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        os.close();
        inputStream.close();
        return outputStream.toByteArray();
    }


    public static void downLoadFile(HttpServletResponse response, HttpServletRequest request, File file) {
        if (file == null || !file.exists()) {
            return;
        }
        String fileName = file.getName();
        OutputStream outputStream = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            //获得浏览器信息并转换为大写
            String agent = request.getHeader("User-Agent").toUpperCase();
            if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {
                //微软的浏览器(IE和Edge浏览器)
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
            response.setHeader("Content-Disposition", "filename=" + fileName);
            outputStream = response.getOutputStream();
            outputStream.write(FileUtils.readFileToByteArray(file));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
